﻿<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8"  %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="ACM.cmsarea08.DBManager" %>

<script language="c#" runat="server">

		void PrintResponse(string message, bool success) {
			Response.ContentType = "text/xml";
			Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			Response.Write( (success?"<done>":"<error>") + message + (success?"</done>":"</error>") );
			return;
		}


		void Page_Load(object o, EventArgs e ) {
			object mioValore =  Request.Form["multixml"];
			object _gruppo   = 	Request.Form["group"];
			object _lingua   = 	Request.Form["lang"];
			object _operazione   = 	Request.Form["operazione"];			
			string gruppo    =  "";
			string lingua = "";
			
			if(_gruppo == null) {
				PrintResponse("no group", false);
				return;
			} else
				gruppo = _gruppo.ToString();
			if(_lingua == null) {
				PrintResponse("no language", false);
				return;
			} else
				lingua = _lingua.ToString();
			if(_operazione!=null) {
				AvviaReset(_operazione,gruppo,lingua);
			}					
			if(mioValore !=null) {
				AvviaElaborazione(mioValore, gruppo, lingua);
			} else 
				PrintResponse("no xml", false);
		}
		
		 const string baseQuery = "insert into {0}user_menu (`role`,`relatedto`, `admin_menu`,`position`,`id`, `order`, `sonof`, `operation`, `nomevoce`,`lang`) " + 
		 					      " values ('group', '{1}', '{2}', 'top',{3},{4},'{5}','{6}','{7}','{8}') ;";
		 const string searchId  = " select max(`id`)+1 from {0}user_menu limit 1; " ;
		 
		 const string resetRole = " delete from {0}user_menu where `relatedto` ='{1}' and lang='{2}'; ";

		void AvviaReset (object xml,string gruppo, string lingua) {
		
			System.Collections.Generic.List<MySqlQuery> elencoQuery= new System.Collections.Generic.List<MySqlQuery>();
			elencoQuery.Add( new MySqlQuery( 
							"deleteAll",
							string.Format(resetRole,"{0}", gruppo,lingua) ,						
							new Replaces[0],MySqlQueryType.ExecuteNonQuery) );
			ACM.cmsarea08.DBManager.DBClass dcb = new ACM.cmsarea08.DBManager.DBClass();
			string reso = dcb.ExecuteTransaction(elencoQuery.ToArray(), true);
			//Response.Write("RESO<br/> : " + reso);
			PrintResponse(reso, true);return;		
		}		 
		
		void AvviaElaborazione (object xml,string gruppo, string lingua) {
			DataSet ds = new DataSet();
			try {
				System.Xml.XmlReader xrd = System.Xml.XmlReader.Create(new System.IO.StringReader(xml.ToString()));
				ds.ReadXml(xrd);
				
				if(ds.Tables.Count==0) {
					PrintResponse("no DATO", false);return;
				}
				if(!ds.Tables.Contains("item")) {
					PrintResponse("no DATO tabella", false);return;
				}
				if(ds.Tables[0].Rows.Count==0) {
					PrintResponse("no DATO righe", false);return;
				}
				ds.Tables["item"].Columns.Add(new DataColumn("query") );				
				ds.Tables["item"].Columns.Add(new DataColumn("operation") );								
				//Response.Write("Elaborazione per gruppo:\"" + gruppo +"\"<br/>");
				DataTable dt = ds.Tables["item"];
				//Response.Write("TABELLA: " + dt.TableName + "<br/>");
				//Response.Write("<table border=\"1\"><tr>");
				//foreach(DataColumn dc in dt.Columns) 
				//	Response.Write("<td style=\"font-weight:bold;\">"+dc.ColumnName + "</td>" );
					
				//Response.Write("<td style=\"font-weight:bold;\">real id</td>" );
				//Response.Write("<td style=\"font-weight:bold;\">admin_menu</td>" );
				//Response.Write("<td style=\"font-weight:bold;\">operation</td>" );
				//Response.Write("<td style=\"font-weight:bold;\">ordine</td>" );
				//Response.Write("<td style=\"font-weight:bold;\">nomeVoce</td>" );				
				//Response.Write("</tr>");
				
				System.Collections.Generic.List<MySqlQuery> elencoQuery= new System.Collections.Generic.List<MySqlQuery>();
				foreach(DataRow dr in dt.Rows) {
					//Response.Write("<tr>");
					//Elaborazione query:
					string id = "";
					string admin_menu = "";
					string operation = "";
					if(dr["enabled"].ToString()=="0") operation="R";
					else {
						if(dr["id"].ToString().StartsWith("new") )
							operation="A";
						else
							operation="S";					
					}

					if(dr["id"].ToString().StartsWith("O")) {
						id = dr["id"].ToString().Substring(1);
						admin_menu = "0";
					} else {
						id="0";
						if( dr["id"].ToString().StartsWith("new") || dr["id"].ToString().StartsWith("C") ) {
							admin_menu = dr["id"].ToString();
							if(operation=="S" && dr["id"].ToString().StartsWith("C") ) {
								admin_menu = "0";
								id = dr["id"].ToString();
							}
						} else
							admin_menu = dr["id"].ToString().Substring(1);
					}	
					string sonof = ( dr["sonof"].ToString()==""?dr["ori-sonof"].ToString():dr["sonof"].ToString() ); 
					if(sonof.StartsWith("new") ) {
						sonof = "C" + sonof;
						dr["sonof"] = sonof;
					}
					if(operation=="R" && dr["id"]!="0")
						sonof="";
						
					string query = string.Format(baseQuery,
						"{0}",gruppo, id, admin_menu, ( dr["order"].ToString()==""?dr["ori-order"].ToString():dr["order"].ToString() ), 
						sonof,operation, 
						( dr["rename"].ToString()==""?dr["ori-name"].ToString():dr["rename"].ToString() ),
						dr["lang"].ToString() );
				
				    if(dr["id"].ToString().StartsWith("new") && operation=="R")
						query="";
				    if(dr["id"].ToString().StartsWith("C") && operation=="R") {
						//nuova query di rimozione per elementi già custom.
						query=string.Format(baseQuery,
						"{0}",gruppo, dr["id"].ToString(), "0", ( dr["order"].ToString()==""?dr["ori-order"].ToString():dr["order"].ToString() ), 
						sonof,operation, 
						( dr["rename"].ToString()==""?dr["ori-name"].ToString():dr["rename"].ToString() ), dr["lang"].ToString() );
					}
						
				//	foreach(DataColumn dc in dt.Columns) 
				//		if(dc.ColumnName!="query") Response.Write("<td>"+dr[dc.ColumnName] + "</td>" );
				//	Response.Write("<td>"+query+"</td>");
				//	Response.Write("<td >"+id+"</td>" );
				//	Response.Write("<td >"+admin_menu+"</td>" );	
				//	Response.Write("<td >"+operation+"</td>" );									
				//	Response.Write("<td >"+( dr["order"].ToString()==""?dr["ori-order"].ToString():dr["order"].ToString() )+"</td>" );								
				//	Response.Write("<td >"+( dr["rename"].ToString()==""?dr["ori-name"].ToString():dr["rename"].ToString() )+"</td>" );								
				//	Response.Write("</tr>");
					dr["query"] = query;
					dr["operation"] = operation;
				}
				//Response.Write("</table><br/>Righe:" + dt.Rows.Count + "<hr/>");
				//avvio elaborazionre...
				//aggiungi query di pulizia:
				elencoQuery.Add( new MySqlQuery( 
							"deleteAll",
							string.Format(resetRole,"{0}", gruppo,lingua) ,						
							new Replaces[0],MySqlQueryType.ExecuteNonQuery) );				
				DataRow[] dExec = dt.Select("","operation asc");
				for(int i = 0 ; i<dExec.Length; i ++) {
					if(dExec[i]["query"].ToString().Trim()=="") continue;
					
					if(dExec[i]["operation"].ToString()=="A") {
						//prendi un valore:
						elencoQuery.Add( new MySqlQuery( 
									dExec[i]["id"].ToString()+ "_ADD",
									searchId,						
									new Replaces[0],MySqlQueryType.ExecuteScalar) );
					}
					if(dExec[i]["operation"].ToString()!="R") {
						
						//string replaceID ="";
						//string replaceIDQuery ="";		
						System.Collections.Generic.List<Replaces> elencoReplace= new System.Collections.Generic.List<Replaces>();
						if(dExec[i]["id"].ToString().StartsWith("new") ) { //|| dExec[i]["id"].ToString().StartsWith("C")) {
							Replaces rep = new Replaces();
							rep.Replace = dExec[i]["id"].ToString();
							rep.ReplaceID = rep.Replace+ "_ADD";
							elencoReplace.Add(rep);
						} 
						 if (dExec[i]["sonof"].ToString().StartsWith("Cnew") ) { //|| dExec[i]["sonof"].ToString().StartsWith("C") ) {
							string tempID ="";bool found=false;
							tempID	= dExec[i]["sonof"].ToString().Substring(1);
							for(int rp=0;rp<elencoReplace.Count;rp++) {
								if(elencoReplace[rp].Replace == tempID) {
									found=true;break;
								}
							}					 
							if(!found) {
								Replaces rep = new Replaces();
								rep.Replace = tempID;
								rep.ReplaceID = rep.Replace+ "_ADD";
								elencoReplace.Add(rep);								
							}
						} 
						
						elencoQuery.Add( new MySqlQuery( 
									dExec[i]["id"].ToString(),
									dExec[i]["query"].ToString(),
									elencoReplace.ToArray(),
									MySqlQueryType.ExecuteNonQuery) );				
					} else {
						elencoQuery.Add( new MySqlQuery( 
									dExec[i]["id"].ToString(),
									dExec[i]["query"].ToString(),
									new Replaces[0],
									MySqlQueryType.ExecuteNonQuery) );						
					
					}
				}
				
				
				//dovrei avere tutte le query pronte...
				/*
				for(int j = 0; j<elencoQuery.Count; j++) {
					Response.Write("QUERY["+ ((MySqlQuery)elencoQuery[j]).QueryID  +"] <br/>" + 
							((MySqlQuery)elencoQuery[j]).Query + " <br>");
							for(int r=0;r<((MySqlQuery)elencoQuery[j]).Replace.Length; r++) {
								Response.Write("REP["+r+"]: " + 
									((MySqlQuery)elencoQuery[j]).Replace[r].Replace + " --> " +
									((MySqlQuery)elencoQuery[j]).Replace[r].ReplaceID + "<br/>");		
							}
					Response.Write("<hr/>");
				}
				*/
				ACM.cmsarea08.DBManager.DBClass dcb = new ACM.cmsarea08.DBManager.DBClass();
				string reso = dcb.ExecuteTransaction(elencoQuery.ToArray(), true);
				//Response.Write("RESO<br/> : " + reso);
				PrintResponse(reso, true);return;
			} catch (Exception ex) {
				PrintResponse(ex.ToString(), false);
			}
		}		
</script>